<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 1.利用递归遍历数据
        var data = [{
            id: 1,
            name: '家电',
            goods: [{
                id: 11,
                gname: '冰箱',
                goods: [{
                    id: 111,
                    gname: '海尔'
                }, {
                    id: 112,
                    gname: '美的'
                }]
            }, {
                id: 12,
                gname: '洗衣机'
            }]
        },
        {
            id: 2,
            name: '服饰'
        }]
        // // 输入对应id 就可以返回数据对象
        function getID(josn, id) {
            var o = {}
            josn.forEach(function (item) {
                if (item.id === id) {
                    o = item
                } else if (item.goods && item.goods.length > 0) {
                    o = getID(item.goods, id)
                }
            })
            return o

        }
        // return会把if判断后的相应数据保存给函数 如果需要这个id数据 就可以直接用这个函数调出来了
        console.log(getID(data, 111));
        console.log(getID(data, 1));
        console.log(getID(data, 2));
        console.log(getID(data, 11));
        console.log(getID(data, 12));



        // function getID(josn, id) {
        //     var o = {}
        //     josn.forEach(function (item) {
        //         if (item.id == id) {
        //             o = item
        //         } else if (item.goods && item.goods.length > 0) {
        //             o = getID(item.goods, id)
        //         }
        //     })
        //     return o
        // }
        // console.log(getID(data, 1));
        // console.log(getID(data, 2));
        // console.log(getID(data, 111));
        // console.log(getID(data, 112));






    </script>
</body>

</html>